package com.gaofans.nrpc.common.protocol;

import com.gaofans.nrpc.common.id.IdGenerator;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * @author GaoFans
 */
@ChannelHandler.Sharable
public class EchoMessageHandler extends ChannelDuplexHandler {

    private final IdGenerator idGenerator;

    public EchoMessageHandler(IdGenerator idGenerator) {
        this.idGenerator = idGenerator;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        if (msg instanceof PingMessage){
            PongMessage pong = new PongMessage();
            PingMessage ping = (PingMessage) msg;
            pong.setSequenceId(ping.getSequenceId());
            ctx.writeAndFlush(pong);
        }else {
            ctx.fireChannelRead(msg);
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
        if (evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.WRITER_IDLE) {
                PingMessage ping = new PingMessage();
                ping.setSequenceId(idGenerator.nextId());
                ctx.writeAndFlush(ping);
            }
            if (event.state() == IdleState.READER_IDLE){
                ctx.channel().close();
            }
        }
    }
}
